package com.icloud.common.web.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.icloud.common.core.api.ResultCode;
import com.icloud.common.web.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@Slf4j
public class HttpClientUtil {

    /**
     * 默认字符集
     */
    private static final String DEFAULT_CHAR_SET = "UTF-8";

    /**
     * 发送post请求
     * @param url
     * @param params
     * @return
     */
    public static JSONObject post(String url, Map<String,Object> params){
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build());

        StringEntity reqEntity = new StringEntity(
                JSONUtil.toJsonStr(params), "utf-8");
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.addHeader("Accept", "application/json");
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClientBuilder.create().build();
            response = httpClient.execute(httpPost);
            String result = null;
            if (null != response.getEntity()) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            return JSONObject.parseObject(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(ResultCode.FAILED);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error("IO异常", e);
            }
        }
    }

    /**
     * 发送get请求
     * @param url
     * @return
     */
    public static JSONObject get(String url,Map<String,Object> params) {
        HttpGet httpGet = new HttpGet(assembleParams(url, params));
        httpGet.addHeader("Content-Type", "application/json;charset=UTF-8");
        httpGet.addHeader("Accept", "application/json");
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClientBuilder.create().build();
            response = httpClient.execute(httpGet);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");

            return JSONObject.parseObject(result);
        }catch (IOException e){
            e.printStackTrace();
            log.error("发送HTTP GET请求异常：{}", e.getMessage());
            return null;
        }finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                log.error("IO异常", e);
            }
        }
    }

    public static String assembleParams(String url, Map<String, Object> params){
        return assembleParams(url,params,DEFAULT_CHAR_SET);
    }

    /**
     * 组装参数
     *
     * @param url     目标地址
     * @param params  参数集合
     * @param charSet 字符编码
     */
    public static String assembleParams(String url, Map<String, Object> params, String charSet) {
        StringBuilder sb = new StringBuilder(url);
        try {
            if (CollectionUtil.isNotEmpty(params)) {
                if (url.contains("?")) {
                    sb.append("&");
                } else {
                    sb.append("?");
                }
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    sb.append(URLEncoder.encode(entry.getKey(), charSet)).append("=")
                            .append(URLEncoder.encode(String.valueOf(entry.getValue()), charSet)).append("&");
                }

                sb.deleteCharAt(sb.length() - 1);
            }
        } catch (UnsupportedEncodingException e) {
            log.info("getUrl异常", e);
        }
        return sb.toString();
    }
}
